package cn.huimin.httpClient.impl;

import cn.huimin.httpClient.AbstractHttpClient;
import cn.huimin.httpClient.IHttpClient;
import cn.huimin.httpClient.ex.URLEmptyException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Martin on 2017-2-27.
 */
public class HMPostRequest extends AbstractHttpClient{

    private static Log logger = LogFactory.getLog(HMPostRequest.class);

    public HMPostRequest() {
    }

    public static IHttpClient getInstance() {
        return new HMPostRequest();
    }

    @Override
    public RequestMethod getMethodType() {
        return RequestMethod.POST;
    }

    @Override
    public String sendData() throws URLEmptyException{

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建httppost
        HttpPost httppost = new HttpPost(client.getPostUrl().toString());

        //设置请求头
        if (client.getHeader() != null && client.getHeader().size() > 0) {
            Map<String, String> map = client.getHeader();
            for (String key : map.keySet()) {
                httppost.setHeader(key, map.get(key));
            }
        }
        // 创建参数队列
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();

        for (Map.Entry<String, Object> entry : client.getParams().entrySet()) {
            if (entry.getValue() instanceof String) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        // 创建httppost
        UrlEncodedFormEntity  uefEntity = null;
        // 执行post请求.
        CloseableHttpResponse response = null;
        try {
            uefEntity = new UrlEncodedFormEntity(formParams, encoding);
            httppost.setEntity(uefEntity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();//设置请求和传输超时时间
            httppost.setConfig(requestConfig);
            logger.info("Executing Request " + httppost.getURI());
            logger.info("Executing Request " + EntityUtils.toString(httppost.getEntity()));

            response = httpclient.execute(httppost);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                logger.info("--------------------------------------------- start");
                responseStatus = response.getStatusLine().getStatusCode() + "";
                logger.info("Response Status: " + responseStatus);
                responseData = EntityUtils.toString(entity, encoding);
                logger.info("Response Content: " + responseData);
                logger.info("--------------------------------------------- end");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseData;
    }



}
